package ifi.p17.jarmanagement;

import ifi.p17.jarmanagement.control.FileProcess;
import ifi.p17.jarmanagement.control.TimeDate;
import ifi.p17.jarmanagement.model.Jar;
import ifi.p17.jarmanagement.model.LogErorr;
import ifi.p17.jarmanagement.model.Purchase;
import ifi.p17.jarmanagement.model.Revenue;
import ifi.p17.jarmanagement.view.AboutPage;
import ifi.p17.jarmanagement.view.HowToUse;
import ifi.p17.jarmanagement.view.Statistics;

import java.util.StringTokenizer;
import java.util.Vector;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

public class MainActivity extends Activity {

	private TextView tv_cur_date;
	Revenue revenu;
	Vector<Jar> jarList;
	TextView tv_cur_depense;
	Button delete, change;
	Purchase cur_depense;
	
	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.main, menu);
		return true;
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		Intent intent = null;
		switch (item.getItemId()) {
		case R.id.action_about:
			intent = new Intent(this, AboutPage.class);
			startActivity(intent);
			return true;
		case R.id.action_howtouse:
			intent = new Intent(this, HowToUse.class);
			startActivity(intent);
			return true;
		case R.id.action_statistics:
			intent = new Intent(this, Statistics.class);
			startActivity(intent);
			return true;
		case R.id.action_settings:
			
			return true;
		default:
			return super.onOptionsItemSelected(item);
		}
		
	}
	
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
		// load variables
		tv_cur_date = (TextView) findViewById(R.id.current_date_tv);
		tv_cur_depense = (TextView) findViewById(R.id.tv_cur_depense);
		delete = (Button) findViewById(R.id.delete_cur_depense);
		change = (Button) findViewById(R.id.change_cur_depense);
		delete.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				if (cur_depense.getType() == Purchase.TYPE_NORMAL){
					actionDeleteCurDepense(v);
				}
			}
		});
		
		change.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				if (cur_depense.getType() == Purchase.TYPE_NORMAL){
					actionChangeCurDepense(v);
				}
			}
		});
		
		// loading components
		preLoad();
		
//		Log.wtf("wtf", "again ???");
	}

	@Override
	protected void onResume() {
		super.onResume();
		tv_cur_date.setText(new TimeDate().getYearMonthDay());

		checkTodayNewMonth();
		calculateTotalEachJar();
		
		drawWindow();
//		Log.wtf("wtf", "again resume???");
	}

	@Override
	protected void onPause() {
		super.onPause();
		FileProcess.writeCurrentSetting(revenu, jarList, cur_depense);
	}
	
	
	
	private void preLoad() {
		// current date
		tv_cur_date.setText(new TimeDate().getYearMonthDay());
		
		// default revenu and jars
		createDefaultData();
		
		if (firstTime()){
			// set all default setting
			
		}else{
			loadCurrentSetting();
		}

		checkTodayNewMonth();
		calculateTotalEachJar();
		
		drawWindow();
	}

	/**************************************************************************/
	
	private void createDefaultData() {
		revenu = new Revenue(this);
		revenu.setTv_revenu((TextView) findViewById(R.id.input_tv2));
		revenu.setTv_remaining((TextView) findViewById(R.id.tv_remaining));
		
		jarList = new Vector<Jar>();
		// set current pepense
		cur_depense = new Purchase();
		
		// create 6 defaults jars
		Jar nec = new Jar(this, getResources().getString(R.string.nec), revenu, cur_depense);
		nec.setTv_jar((TextView) findViewById(R.id.tv_jar_nec));
		nec.setTv_proc((TextView) findViewById(R.id.tv_proc_nec));
	
		Jar ffa = new Jar(this, getResources().getString(R.string.ffa), revenu, cur_depense);
		ffa.setTv_jar((TextView) findViewById(R.id.tv_jar_ffa));
		ffa.setTv_proc((TextView) findViewById(R.id.tv_proc_ffa));

		Jar ltss = new Jar(this, getResources().getString(R.string.ltss), revenu, cur_depense);
		ltss.setTv_jar((TextView) findViewById(R.id.tv_jar_ltss));
		ltss.setTv_proc((TextView) findViewById(R.id.tv_proc_ltss));
		
		Jar edu = new Jar(this, getResources().getString(R.string.edu), revenu, cur_depense);
		edu.setTv_jar((TextView) findViewById(R.id.tv_jar_edu));
		edu.setTv_proc((TextView) findViewById(R.id.tv_proc_edu));

		Jar play = new Jar(this, getResources().getString(R.string.play), revenu, cur_depense);
		play.setTv_jar((TextView) findViewById(R.id.tv_jar_play));
		play.setTv_proc((TextView) findViewById(R.id.tv_proc_play));

		Jar give = new Jar(this, getResources().getString(R.string.give), revenu, cur_depense);
		give.setTv_jar((TextView) findViewById(R.id.tv_jar_give));
		give.setTv_proc((TextView) findViewById(R.id.tv_proc_give));

		// set default percent
		nec.setPercent(Jar.NEC_DEFAULT);
		ffa.setPercent(Jar.FFA_DEFAULT);
		ltss.setPercent(Jar.LTSS_DEFAULT);
		edu.setPercent(Jar.EDU_DEFAULT);
		play.setPercent(Jar.PLAY_DEFAULT);
		give.setPercent(Jar.GIVE_DEFAULT);
		
		// add in list
		jarList.add(nec);
		jarList.add(ffa);
		jarList.add(ltss);
		jarList.add(edu);
		jarList.add(play);
		jarList.add(give);

	}

	public void calculateTotalEachJar(){
		int remain = revenu.getAmount();
		int remain_rev = revenu.getAmount();
		for (Jar jar : jarList)
			if (jar.getName().compareTo(getResources().getString(R.string.give)) != 0){
				jar.setTotal(revenu.getAmount() * jar.getPercent() / 100);
				remain -= jar.getTotal();
				jar.setUnit(revenu.getUnit());
				
				remain_rev -= jar.getCurrent();
			}
			
		for (Jar jar : jarList)
			if (jar.getName().compareTo(getResources().getString(R.string.give)) == 0){
				jar.setTotal(remain);
				jar.setUnit(revenu.getUnit());
				remain_rev -= jar.getCurrent();
				break;
			}
		
		revenu.setRemaining(remain_rev);
	}
	
	public void drawWindow() {
		revenu.updateText();
		for (Jar jar : jarList) jar.updateJar();
		if (cur_depense.getType() == Purchase.TYPE_NULL) tv_cur_depense.setText("NO CURRENT DEPENSE");
		else {
			LogErorr.out(cur_depense.toString());
			tv_cur_depense.setText(cur_depense.getTime()
					+ " - " + cur_depense.getValue() 
					+ " (" + cur_depense.getUnit()
					+ ") - " + cur_depense.getJar());
		}
	}

	private boolean firstTime() {
		return ! FileProcess.fileExist(FileProcess.HOME_DIR + FileProcess.APP_DIR + FileProcess.SETTING_FILE);
	}

	private void loadCurrentSetting() {
		FileProcess.loadSettingFromFile(revenu, jarList, cur_depense);
	}

	private void checkTodayNewMonth(){
		TimeDate timedate = new TimeDate(); 
				
		if (timedate.getDay().compareTo("1") == 0 
				&& FileProcess.fileExist(
						FileProcess.HOME_DIR + FileProcess.APP_DIR + timedate.getYearMonthDay())
				) {
			revenu.setRemaining(revenu.getAmount());
			revenu.updateText();
			for (Jar jar : jarList) jar.setCurrent(0);
		}
	}
	

	protected void actionDeleteCurDepense(View v) {
		AlertDialog.Builder builder = new AlertDialog.Builder(v.getContext());
		
		builder.setMessage("Do you want to delete the current depense ?");
				
		
		builder
			.setCancelable(false)
			.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
				
				@Override
				public void onClick(DialogInterface dialog, int which) {
					deleteCurrentDepense();
				}
			})
			.setNegativeButton("No", new DialogInterface.OnClickListener() {
				
				@Override
				public void onClick(DialogInterface dialog, int which) {
					dialog.cancel();
				}
			});
		
		AlertDialog alert = builder.create();
		alert.show();

		
	}

	protected void deleteCurrentDepense() {
		Vector<Purchase> list_of_day = new Vector<Purchase>();
		StringTokenizer time = new StringTokenizer(cur_depense.getTime());
		String filedate = time.nextToken();
		
		FileProcess.loadAllPurchaseOfDate(filedate, list_of_day);
		int index = -1;
		for (int i=list_of_day.size()-1; i>=0; i--)
			if (list_of_day.get(i).getTime().compareTo(cur_depense.getTime()) == 0) {
				index = i;
				break;
			}
		
		if (index>-1){
			int jar_index = -1;
			for (int i=0; i<jarList.size(); i++)
				if (cur_depense.getJar().compareTo(jarList.get(i).getName()) == 0){
					jar_index = i;
					break;
				}
			jarList.get(jar_index).addCurrent(-cur_depense.getValue());
			list_of_day.remove(index);
			FileProcess.writeAllPurchaseOfDate(filedate, list_of_day);
			cur_depense.setType(Purchase.TYPE_NULL);
			calculateTotalEachJar();
			
			String data2 = Integer.toString(revenu.getAmount()) + " " + Integer.toString(revenu.getRemaining());
			StringTokenizer st2 = new StringTokenizer(filedate,"/");
			String folder = st2.nextToken() + "/" + st2.nextToken();
			FileProcess.writeToFile(data2, folder, FileProcess.REMAINING_FILE, false);

			drawWindow();
		}
	}

	protected void actionChangeCurDepense(View v) {
		LayoutInflater layoutInflater = LayoutInflater.from(v.getContext());
		
		View promptView = layoutInflater.inflate(R.layout.purchase_change, null);

		AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(v.getContext());

		// set prompts.xml to be the layout file of the alertdialog builder
		alertDialogBuilder.setView(promptView);

		
		final TextView timejar = (TextView) promptView.findViewById(R.id.timejar);
		final EditText input = (EditText) promptView.findViewById(R.id.value_cur_depense);
		final EditText des_input = (EditText) promptView.findViewById(R.id.des_change_depense);

		timejar.setText(cur_depense.getTime() + " - " + cur_depense.getUnit());
		input.setText(Integer.toString(cur_depense.getValue()));
		des_input.setText(cur_depense.getDescription());
		// setup a dialog window

		alertDialogBuilder
				.setCancelable(false)
				.setPositiveButton("OK", new DialogInterface.OnClickListener() {
							public void onClick(DialogInterface dialog, int id) {
								// get user input and set it to result
								String in = input.getText().toString();
								if (in!=null && in.length()>0){
									int pur = Integer.parseInt(input.getText().toString());
									String des = des_input.getText().toString();
									updateCurrentPurchase(pur, des);
									
								}
							}
						})
				.setNegativeButton("Cancel",
						new DialogInterface.OnClickListener() {
							public void onClick(DialogInterface dialog,	int id) {
								dialog.cancel();
							}
						});

		// create an alert dialog
		AlertDialog alertD = alertDialogBuilder.create();

		alertD.show();

	}

	protected void updateCurrentPurchase(int pur, String des) {
		Vector<Purchase> list_of_day = new Vector<Purchase>();
		StringTokenizer time = new StringTokenizer(cur_depense.getTime());
		String filedate = time.nextToken();
		
		FileProcess.loadAllPurchaseOfDate(filedate, list_of_day);
		int index = -1;
		for (int i=list_of_day.size()-1; i>=0; i--)
			if (list_of_day.get(i).getTime().compareTo(cur_depense.getTime()) == 0) {
				index = i;
				break;
			}
		
		if (index>-1){
			int jar_index = -1;
			for (int i=0; i<jarList.size(); i++)
				if (cur_depense.getJar().compareTo(jarList.get(i).getName()) == 0){
					jar_index = i;
					break;
				}
			if (pur == 0 || pur - cur_depense.getValue() > jarList.get(jar_index).getTotal() - jarList.get(jar_index).getCurrent()){
				AlertDialog.Builder builder = new AlertDialog.Builder(this);
				
				builder.setMessage("Out of JAR")
						.setTitle("Error");
				
				builder
					.setCancelable(false)
					.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
						
						@Override
						public void onClick(DialogInterface dialog, int which) {
							dialog.cancel();
						}
					});
				
				AlertDialog alert = builder.create();
				alert.show();
			}else {
				jarList.get(jar_index).addCurrent(pur - cur_depense.getValue() );
				list_of_day.remove(index);
				cur_depense.setValue(pur);
				cur_depense.setDescription(des);
				list_of_day.add(cur_depense);
				FileProcess.writeAllPurchaseOfDate(filedate, list_of_day);
				calculateTotalEachJar();

				String data2 = Integer.toString(revenu.getAmount()) + " " + Integer.toString(revenu.getRemaining());
				StringTokenizer st2 = new StringTokenizer(filedate,"/");
				String folder = st2.nextToken() + "/" + st2.nextToken();
				FileProcess.writeToFile(data2, folder, FileProcess.REMAINING_FILE, false);
				
				drawWindow();
			}
		}
		
	}



}
